package com.neusoft.elmboot;

import org.springframework.context.annotation.Configuration;

import com.neusoft.elmboot.config.XSSRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class WebMvcConfig  implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600");

        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }
        if (!(req instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
            throw new ServletException("XssFilter just supports HTTP requests");
        }else {
            HttpServletRequest request = (HttpServletRequest) req;
            XSSRequestWrapper wrappedRequest = new XSSRequestWrapper(request);
            chain.doFilter(wrappedRequest, response);
        }
    }
}
